/*
 * @Author: kanglang
 * @Date: 2021-02-23 13:24:37
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-21 16:28:18
 * @Description: 设置
 */
import React, { Component } from 'react';
import { NativeModules, StyleSheet, Text, TouchableOpacity, SafeAreaView } from 'react-native';
import api from '@/api';
import { msg, SyncStorage, cache } from '@/common';
import { px2dp, isAndroid, mainBgColorLightGray } from '@/styles';
import { ListItem } from '@/components';
import { getAgreementByArray } from '@/common/agreement-version';
import baseConfig from '@/config/baseConfig';

const { terminalCode } = baseConfig;
const CookieManager = NativeModules.RNCookieManagerIOS;
export default class Setting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      appVersion: null,
      articlesList: []
    };
  }

  componentDidMount() {
    this.getSystemInfo();
    // 查询隐私协议版本
    getAgreementByArray(
      [{ appCode: terminalCode, code: 'agreement', }, { appCode: terminalCode, code: 'privacyAgreement', }, { appCode: terminalCode, code: 'PerInfoAgreement', }],
      (data) => {
        this.setState({ articlesList: data });
      },
    );
  }

  render() {
    const { appVersion, articlesList } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        {articlesList.map((item, index) => {
          return <ListItem
            title={item.title}
            titleStyle={{ fontSize: px2dp(28) }}
            style={{ paddingHorizontal: px2dp(32), }}
            rightBoxStyle={(index === (articlesList.length - 1)) && { borderBottomWidth: 0 }}
            onClick={() => { this.jumpAgreement(item); }}
          />;
        })}

        <ListItem
          title='版本号'
          titleStyle={{ fontSize: px2dp(28) }}
          style={{ paddingHorizontal: px2dp(32), marginTop: px2dp(24) }}
          rightBoxStyle={{ borderBottomWidth: 0 }}
          extra={appVersion && `v${appVersion}`}
          arrow='empty'
          onClick={() => this._getApk()}
        />
        <TouchableOpacity
          activeOpacity={1}
          onPress={() => this._loginout()}
          style={styles.logoutWrap}
        >
          <Text style={styles.logoutText}>退出当前账号</Text>
        </TouchableOpacity>
      </SafeAreaView>
    );
  }

  getSystemInfo=() => {
    NativeModules.BridgeManager.getSystemInfo((systemInfo) => {
      this.setState({ appVersion: systemInfo.appVersion });
    });
  }

  jumpAgreement = (data) => {
    msg.emit('router: goToNext', {
      routeName: 'CustAgreement',
      title: data.title,
      content: data.content,
    });
  };

  _getApk = () => {
    NativeModules.DataModule.checkVersion('setting'); // 检测升级
  };

  _loginout = () => {
    msg.emit('app:messageBox', {
      isVisible: true,
      text: '确定要退出当前账号吗？',
      okText: '确定',
      cancelText: '取消',
      okFn: () => {
        api.user
          .logout()
          .then((res) => {
            if (res.success) {
              if (__DEV__) {
                console.log('退出登录成功');
              }
              SyncStorage.removeItem(cache.USER_INFO);
              SyncStorage.removeItem(cache.ROLE);
              SyncStorage.removeItem(cache.TOKEN_ID);
              if (!isAndroid) {
                CookieManager.clearAll().then((res) => {
                  console.log('CookieManager.clearAll =>', res);
                });
              }
              msg.emit('router: reset', {
                routeName: 'LoginView',
              });
            } else {
              msg.emit('app:messageBox', {
                isVisible: true,
                title: '温馨提示',
                text: res.msg,
                okText: '确定',
              });
            }
          })
          .catch((res) => {
            if (__DEV__) {
              console.log(`退出异常：${res}`);
            }

            msg.emit('app:messageBox', {
              isVisible: true,
              title: '温馨提示',
              text: '退出异常',
              okText: '确定',
            });
          });
      },
      cancelFn: () => {
        console.log('🚀🚀🚀wimi======>>>cancelFn',);
      },
    });
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
    position: 'relative',
    paddingTop: px2dp(24)
  },
  logoutText: {
    color: 'red',
  },
  logoutWrap: {
    position: 'absolute',
    bottom: 0,
    height: px2dp(148),
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    paddingBottom: px2dp(40)
  },

});
